#include "clientwaitpool.h"
#include "client.h"

ClientWaitPool *ClientWaitPool::m_instance = 0;

QMutex ClientWaitPool::m_mutex;

ClientWaitPool::ClientWaitPool()
{
    if(m_waitClientList == NULL)
    {

        m_waitClientList = new QMap<unsigned int, Client*>();
    }
}

ClientWaitPool::~ClientWaitPool()
{
    if(m_waitClientList != NULL)
    {
        if(!m_waitClientList->empty())
        {
            QMap<unsigned int, Client*>::iterator i = m_waitClientList->begin();
            QMap<unsigned int, Client*>::iterator j = i;
            while( i != m_waitClientList->end())
            {
                j = m_waitClientList->erase(i);
                delete i.value();

                i = j;
            }
            // remove error
        }

        delete m_waitClientList;
    }
}

int ClientWaitPool::removeWaitClient(unsigned int request_id)
{
    QMutexLocker locker(&m_mutex);

    QMap<unsigned int, Client*>::iterator i = m_waitClientList->find(request_id);
    if( i == m_waitClientList->end())
    {
        return -1;
    }
    int count = m_waitClientList->remove(request_id);
    if(count >1)
    {
        // 2 more has same session id
        // can not happen
        return -2;
    }

    delete i.value();

}

int ClientWaitPool::addWaitClient(Client *client)
{
    QMutexLocker locker(&m_mutex);

    if(m_waitClientList == NULL)
    {
        return -1;
    }

    QMap<unsigned int, Client*>::iterator i = m_waitClientList->find(client->getRequestID());
    if(i != m_waitClientList->end())
    {
        //check why has same id
        // this can not happen
        return -1;
    }

    m_waitClientList->insert(client->getRequestID(), client);
    return 0;
}

Client *ClientWaitPool::getWaitClient(unsigned int request_id)
{
    QMutexLocker locker(&m_mutex);

    if(m_waitClientList == NULL)
    {
        return NULL;
    }
    return (*m_waitClientList)[request_id];
}
